﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using WpfClient.TransitODataServiceReference;
using System.Collections.Generic;

namespace WpfClient
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow
	{
		private readonly string _serviceUrl ;
	    private readonly ObservableCollection<object> _observableCollection;
	    private readonly CollectionViewSource _source;
	    private TransitData _context;

	    public MainWindow()
		{
			InitializeComponent();

			_serviceUrl = ConfigurationManager.AppSettings.Get("TransitODataServiceUrl");
            var uri = new Uri(_serviceUrl, UriKind.Absolute);
            _context = new TransitData(uri);
		    _observableCollection = new ObservableCollection<object>();
            _source = (CollectionViewSource)_grid.Resources["_source"];
            _source.Source = _observableCollection;
            AgenciesButton.Click += OnExecuteButtonClick;
            StopsButton.Click += OnExecuteStopsButtonClick;
            ItinerariesButton.Click += OnExecuteItinerariesButtonClick;
		}

	    private void OnExecuteItinerariesButtonClick(object sender, RoutedEventArgs e)
	    { 
            

	        //TransitODataService.svc/CalculateItineraryByStops?stop1Id='11868'&stop2Id='11882'&startTime=datetime'2009-12-26T01:23:38Z'
	        var queryUri = string.Format("{0}CalculateItineraryByStops?stop1Id='{1}'&stop2Id='{2}'&startTime=datetime'{3}'&$expand=Legs", _context.BaseUri, "11868", "11882", "2009-12-26T01:23:38Z");


	        AsyncCallback callback = delegate(IAsyncResult ar)
	                                     {
	                                         var itineraries = _context.EndExecute<Itinerary>(ar);
                                             if (itineraries != null)
                                                 foreach (var itinerary in itineraries)
                                                 {
                                                     _observableCollection.Add(string.Format("Departure time:{0}, Arrival time:{1}, Transfers:{2}", itinerary.StartTime, itinerary.EndTime, itinerary.TravelTypes));
                                                 }
	                                     };
	        _context.BeginExecute<Itinerary>(new Uri(queryUri, UriKind.RelativeOrAbsolute), callback, null);
	    }

	

	    private void OnExecuteStopsButtonClick(object sender, RoutedEventArgs e)
	    {
            var area = (from geoArea in _context.GeoAreas.Expand("Stops")
                            where geoArea.ID == "38.996796|-76.904472|0.05"
                            select geoArea).FirstOrDefault();

           _observableCollection.Add(string.Format("Area lat:{0},lon:{1},radius:{2} miles contains follow stops:", area.Lat1,area.Lon1,area.Radius));
	        
            foreach (var stop in area.Stops)
	        {
	            _observableCollection.Add("\t"+ stop.Name);
	        }
          
	    }

	    private void OnExecuteButtonClick(object sender, RoutedEventArgs e)
		{
	
		    foreach (var agency in from agency in _context.Agencies 
                                   select new
                                              {
                                                  agency.Name, 
                                                  StateName = agency.State.Name
                                              })
		    {
		        _observableCollection.Add(string.Format("{0} ({1})", agency.Name, agency.StateName));
		    }

		}
	}
}
